﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;

namespace eDonkeyAPI
{
    public class RepToXML
    {
        public delegate void ConvertProgress(int precentage);
        public static event ConvertProgress Progress;
        public static event EventHandler StartConvertion;
      #region Regular Expressions Constants
      /// <summary>
      /// TODO
      /// Regex for:
      /// (Faculty:
            /// 
            /// +=====+
            /// | XXX |
            /// +=====+
            ///   XXX )*
            /// </summary>
            private const string FILE_REGEX = @"";
            #region Faculty
            /// <summary>
            /// Regex for:
            /// +=================+
            /// | Faculties Header|
            /// +=================+
            /// +-----------------+
            /// (Course
            /// +-----------------+
            ///        XXX
            /// +-----------------+
            /// +)*
            /// </summary>
            private const string FACULTY_REGEX =
                @"\+=+\+(?<FacultyHeader>[^+]*)\+=+\+[^+]*\+-+\+" + //Faculty Header
                @"(?<Course>.*?\+-+\+.*?\+-+\+)*"; //Course
            /// <summary>
            /// Regex for:
            /// | FacultyName - XXX |
            /// | Semster ñîñèø  |
            /// or
            /// | Semster ñîñèø  - FacultyName |
            /// </summary>
            private const string FACULTY_HEADER_REGEX =
                @"\|\s+(?<FacultyName>[^-]+)-.*\|.*\|\s+(?<Semster>.*)רטסמס\s+\|" +
                "|" +
                @"\|\s+(?<Semster>.*)רטסמס - (?<FacultyName>[^|]+)\|";

            private const string FACULTY_SEPERATOR = "\r\n\r\n";
            #endregion Faculty
            #region Course
            /// <summary>
            /// Regex for:
            /// +--------------+
            /// | CourseHeader |
            /// +--------------+
            /// | CourseParams |
            /// </summary>
            private const string COURSE_REGEX =
                @"(?<CourseHeader>.*)\+-+\+(?<CourseParams>.*)\+-+\+";
            /// <summary>
            /// Regex for:
            /// | CourseNumber CourseID                   |
            /// | CourseAcademicPoint:ð÷ CourseHours:XXX  |
            /// </summary>
            private const string COURSE_HEADER =
                "\\|\\s*(?<CourseName>.*)\\s+(?<CourseNumber>\\d+?)\\s+\\|\r\n" +
                "\\|(?<CourseAcademicPoints>[^:]+):קנ(?<CourseHours>[^:]+).*\\|";
            /// <summary>
            /// Regex for:
            /// | LacturerInCharge : îåøä àçøàé |
            /// | -+                            |
            /// | FirstTestDate    : îåòã øàùåï |
            /// | -+                            |
            /// | SecondTestDate     : îåòã ùðé |
            /// | -+                            |
            /// </summary>
            private const string COURSE_BODY =
                "\r\n" +
                "(\\|(?<LacturerInCharge>.*): יארחא  הרומ \\|\r\n" +
                "\\|\\s*-+\\s*\\|\r\n)?" +
                "(\\|(?<FirstTestDate>.*)\\s+םוי: ןושאר דעומ \\|\r\n" +
                "\\|\\s*-+\\s*\\|\r\n)?" +
                "(\\|(?<SecondTestDate>.*)םוי:   ינש דעומ \\|\r\n" +
                "\\|\\s*-+\\s*\\|\r\n)?";

            /// <summary>
            /// Regex for:
            ///(|               ++++++                  .îñ|
            /// |                                     øéùåí| Or
            /// |                                          |)
            /// |(Building) (Room)   Hours'Day (:)Type (No)|
            ///(|(Building) (Room)   Hours'Day             |)
            ///(|                     GiverName : GiverType|
            /// |                               -----      |)
            /// </summary>
            private const string COURSE_GROUPS =
                "((?<PlaceTime>\\|\\s*([^|]+)?(\\s+\\d+)?\\s+(\\d{1,2}.\\d{2}-\\s?\\d{1,2}.\\d{2}'\\w{1})\\s*\\|\r\n)?" +
                "(?<Header>\\|\\s+\\++\\s+.ñî\\|\r\n" +
                "\\|\\s+íåùéø\\|\r\n)" +
                "|" +
                "\\|\\s+\\|\r\n)?" +
                "\\|(\\s*(?<Place>[^|]+)?\\s+(?<DayTime>\\d{1,2}.\\d{2}-\\s?\\d{1,2}.\\d{2}'\\w{1})|\\s*-\\s*)\\s+:?\\s*(?<GroupType>.*?)\\s+(?<Number>\\d{2})?\\s+\\|\r\n" +
                "(?<PlaceTime>\\|\\s*([^|]+)?(\\s+\\d+)?\\s+(\\d{1,2}.\\d{2}-\\s?\\d{1,2}.\\d{2}'\\w{1})\\s*\\|\r\n)*" +
                "(\\|\\s+(?<Giver>[^|]*) : (?<GiverType>\\w+)\\s+\\|\r\n" +
                "\\|\\s+-+\\s+\\|\r\n)?";
            private const string COURSE_PLACE_TIME =
                "\\|\\s*(?<Place>[^|]+)?\\s+(?<DayTime>\\d{1,2}.\\d{2}-\\s?\\d{1,2}.\\d{2}'\\w{1})\\s*\\|\r\n";
            #endregion Course
            #endregion Regular Expressions Constants
            #region Static Methods
            #region Public Methods
            /*public static void Convert( object fileName, string toFile  )
		{
			RepToXML.Convert( fileName as string );
		}*/
      public static void Convert(string fileName, string toFile)
      {
        string file = DosHeb.Translate(fileName);
        //StartConvertion(null, new EventArgs());
        ConvertFiles(file, toFile);
      }
     #endregion Public Methods
     #region Private Convert Methods
     private static void ConvertFiles(string file, string toFile)
     {
        DBSerialBuilder.startSerialBuild(toFile);
        int currentFaculty = 0;
        int numOfFaculties = 0;

        int lastIndex = 0;
        for (int index = file.IndexOf(FACULTY_SEPERATOR, 0);
            lastIndex != -1;
            index = file.IndexOf(FACULTY_SEPERATOR, lastIndex + FACULTY_SEPERATOR.Length))
        {
            int to = (index == -1) ? file.Length : index;
            numOfFaculties++;
            lastIndex = index;
        }

        //Progress(0);
        lastIndex = 0;
        for (int index = file.IndexOf(FACULTY_SEPERATOR, 0);
                    lastIndex != -1;
                    index = file.IndexOf(FACULTY_SEPERATOR, lastIndex + FACULTY_SEPERATOR.Length))
        {
            int to = (index == -1) ? file.Length : index;
            ConvertFaculty(file.Substring(lastIndex, to - lastIndex));
            //Progress(++currentFaculty * 100 / numOfFaculties);
            lastIndex = index;
        }
                //Progress(100);

                /*TODO When FILE_REGEX will be comleted
                Regex regex = new Regex( FILE_REGEX, RegexOptions.Singleline );
                Match match = regex.Match( file ) ;
                Group faculty = match.Groups[ "Faculty" ];
                foreach( Capture capture in faculty.Captures )
                {
                    result += ConvertFaculty( capture.Value );
                }*/
                DBSerialBuilder.endSerialBuild();
     }
            #region Faculty
            private static void ConvertFaculty(string faculty)
            {
                faculty = faculty.Trim();
                if (faculty.Length == 0)
                    return;

                Regex regex = new Regex(FACULTY_REGEX, RegexOptions.Singleline);
                for (Match match = regex.Match(faculty);
                    match != Match.Empty;
                    match = match.NextMatch())
                {
                    ConvertFacultysHeader(match.Groups["FacultyHeader"].Value);

                    Group course = match.Groups["Course"];
                    foreach (Capture capture in course.Captures)
                    {
                        ConvertCourse(capture.Value);
                    }
                }
                DBSerialBuilder.closeFaculty();
            }
            private static void ConvertFacultysHeader(string header)
            {
                Regex regex = new Regex(FACULTY_HEADER_REGEX, RegexOptions.Singleline);

                Match match = regex.Match(header);

                string facultyName = DosHeb.Revert(match.Groups["FacultyName"].Value.Trim());
                string semster = DosHeb.Revert(match.Groups["Semster"].Value.Trim());

                DBSerialBuilder.startFaculty(facultyName, semster);
            }
            #endregion Faculty
            #region Course
            private static void ConvertCourse(string course)
            {
                Regex regex = new Regex(COURSE_REGEX, RegexOptions.Singleline);

                for (Match match = regex.Match(course);
                    match != Match.Empty;
                    match = match.NextMatch())
                {
                    ConvertCoursesHeader(match.Groups["CourseHeader"].Value);
                    ConvertCoursesBody(match.Groups["CourseParams"].Value);
                    DBSerialBuilder.closeCourse();
                }
            }
            private static void ConvertCoursesHeader(string header)
            {
                Regex regex = new Regex(COURSE_HEADER);
                Match match = regex.Match(header);

                string courseName = DosHeb.Revert(match.Groups["CourseName"].Value.Trim());
                string courseNumber = match.Groups["CourseNumber"].Value.Trim();
                string academicPoints = match.Groups["CourseAcademicPoints"].Value.Trim();
                string[] courseHours = ConvertCoursesHourse(DosHeb.Revert(match.Groups["CourseHours"].Value.Trim()));
                //HERE!
                DBSerialBuilder.startCourse(courseName, courseNumber, academicPoints,
                    courseHours[0], courseHours[1], courseHours[2], courseHours[3]);
            }
            private static void ConvertCoursesBody(string body)
            {
                Regex regex = new Regex(COURSE_BODY, RegexOptions.RightToLeft);

                //Find the longest match (starts at the begining)
                Match match;
                for (match = regex.Match(body);
                    match.Index != 0 && match != Match.Empty;
                    match = match.NextMatch()) ;

                string lacturerInCharge = DosHeb.Revert(match.Groups["LacturerInCharge"].Value.Trim());
                string firstTestDate = match.Groups["FirstTestDate"].Value.Split('\'')[0].Trim();
                string secondTestDate = match.Groups["SecondTestDate"].Value.Split('\'')[0].Trim();
                DBSerialBuilder.addCourseDetails(lacturerInCharge, firstTestDate, secondTestDate);
                //HERE!
                ConvertCoursesGroups(body.Substring(match.Index + match.Length));
            }
            private static void ConvertCoursesGroups(string groups)
            {
                Regex regex = new Regex(COURSE_GROUPS);

                for (Match match = regex.Match(groups);
                    match != Match.Empty;
                    match = match.NextMatch())
                {
                    string header = DosHeb.Revert(match.Groups["Header"].Value.Trim());
                    string groupType = DosHeb.Revert(match.Groups["GroupType"].Value.Trim());
                    string[] dayTime = match.Groups["DayTime"].Value.Trim().Split('\'');
                    string day = string.Empty;
                    string start = string.Empty;
                    string duration = string.Empty;
                    if (dayTime[0].Length != 0)
                    {
                        day = dayTime[1];
                        start = GetStartTime(dayTime[0]);
                        duration = GetDuration(dayTime[0]);
                    }
                    string place = GetPlace(match.Groups["Place"].Value.Trim());
                    string giverType = DosHeb.Revert(match.Groups["GiverType"].Value.Trim());
                    string giver = DosHeb.Revert(match.Groups["Giver"].Value.Trim());
                    string regNumber = match.Groups["Number"].Value.Trim();
                    //HERE!
                    DBSerialBuilder.startGroupEvent(regNumber, groupType, giver);
                    DBSerialBuilder.addPlaceTime(day, start, duration, place);

                    Group events = match.Groups["PlaceTime"];
                    foreach (Capture capture in events.Captures)
                    {
                        ConvertPlaceTime(capture.Value);
                    }

                    DBSerialBuilder.closeGroupEvent();
                }
            }
            private static void ConvertPlaceTime(string placeTime)
            {
                Regex regex = new Regex(COURSE_PLACE_TIME);
                Match match = regex.Match(placeTime);

                if (match == Match.Empty) return;

                string[] dayTime = match.Groups["DayTime"].Value.Trim().Split('\'');
                string day = string.Empty;
                string start = string.Empty;
                string duration = string.Empty;
                if (dayTime[0].Length != 0)
                {
                    day = dayTime[1];
                    start = GetStartTime(dayTime[0]);
                    duration = GetDuration(dayTime[0]);
                }
                string place = GetPlace(match.Groups["Place"].Value.Trim());
                //HERE!
                DBSerialBuilder.addPlaceTime(day, start, duration, place);
            }

            private static string[] ConvertCoursesHourse(string hours)
            {
                string[] retHours = new string[] {   string.Empty, 
												 string.Empty, 
												 string.Empty, 
												 string.Empty };
                string[] hoursSplits = hours.Split(' ');
                foreach (string hour in hoursSplits)
                {
                    if (hour.Length == 0)
                    {
                        continue;
                    }
                    string[] hourSplit = hour.Split('-');
                    switch (hourSplit[0])
                    {
                        case "ה":
                            {
                                retHours[0] = hourSplit[1];
                                break;
                            }
                        case "ק":
                            {
                                retHours[1] = hourSplit[1];
                                break;
                            }
                        case "ם":
                            {
                                retHours[2] = hourSplit[1];
                                break;
                            }
                        case "ף":
                            {
                                retHours[3] = hourSplit[1];
                                break;
                            }
                        /*default:
                            {
                                //throw new ArgumentOutOfRangeException("hours", hours, "Do know " + hourSplit[0]);
                            }*/
                    }
                }
                return retHours;
            }
            private static string GetStartTime(string time)
            {
                return time.Split('-')[0];
            }
            private static string GetDuration(string time)
            {
                if (time.Length == 0)
                {
                    return string.Empty;
                }
                string[] timeSplit = time.Split('-');

                int start = int.Parse(timeSplit[0].Split('.')[1]) == 30 ?
                    int.Parse(timeSplit[0].Split('.')[0]) :
                    int.Parse(timeSplit[0].Split('.')[0]) - 1;

                int end = int.Parse(timeSplit[1].Split('.')[0]);

                return (end - start).ToString();
            }
            private static string GetPlace(string place)
            {
                string[] split = place.Split();
                string ret = string.Empty;
                foreach (string s in split)
                {
                    string t = s;
                    try
                    {
                        int i = int.Parse(s);
                        ret += string.Format("{0}{1}",
                            (ret.Length == 0) ? string.Empty : " ", t);
                    }
                    catch
                    {
                        //Revert the hebrew string
                        t = DosHeb.Revert(s);
                        //Add the string at the begining.
                        ret = string.Format("{1}{0}{2}",
                            (ret.Length == 0) ? string.Empty : " ", t, ret);
                    }

                }
                return ret;
            }
            #endregion Course
            #endregion Private Convert Methods
            #endregion Static Methods
            #region Constructors
            /// <summary>
            /// Private Constructor to prevent instances of this class
            /// </summary>
            private RepToXML()
            {
            }
            #endregion Constructors
    }
    public class DosHeb
	{
        #region Translate Table and EOL
        //http://www.kostis.net/charsets/cp862.htm
        static char[] TRANSLATE_TABLE = {
                                            /*  0*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /* 10*/'\n',' ',' ','\r',' ',' ',' ',' ',' ',' ',
                                            /* 20*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /* 30*/' ',' ',' ','!','\'','#','$','%','&','\'',
                                            /* 40*/')','(','*','+',',','-','.','/','0','1',
                                            /* 50*/'2','3','4','5','6','7','8','9',':',';',
                                            /* 60*/'<','=','>','?','@','A','B','C','D','E',
                                            /* 70*/'F','G','H','I','J','K','L','M','N','O',
                                            /* 80*/'P','Q','R','S','T','U','V','W','X','Y',
                                            /* 90*/'Z','[','\\',']','^','_','\'','a','b','c',
                                            /*100*/'d','e','f','g','h','i','j','k','l','m',
                                            /*110*/'n','o','p','q','r','s','t','u','v','w',
                                            /*120*/'x','y','z','{','|','}','~',' ','א','ב',
                                            /*130*/'ג','ד','ה','ו','ז','ח','ט','י','ך','כ',
                                            /*140*/'ל','ם','מ','ן','נ','ס','ע','ף','פ','ץ',
                                            /*150*/'צ','ק','ר','ש','ת',' ',' ',' ',' ',' ',
                                            /*160*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /*170*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /*180*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /*190*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /*200*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /*210*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /*220*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /*230*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /*240*/' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',
                                            /*250*/' ',' ',' ',' ',' ',' '};
        static char[] END_OF_LINE = {'\r','\n'};
        #endregion Translate Table and EOL
        #region Static Methods
        /// <summary>
        /// Reads DosHeb file's content andtranslate it to Unicode
        /// </summary>
        /// <param name="fileName">File that contains DosHeb text</param>
        /// <returns>Files input translated to Unicode</returns>
        public static string Translate( string fileName )
        {
            FileStream fileReader = File.OpenRead( fileName ) ;
            byte[] fileBytes = new byte[fileReader.Length];
            //Read the file as bytes to avoid encoding and ruin it
            fileReader.Read( fileBytes, 0, fileBytes.Length );
            fileReader.Close();

            //Translate the file's bytes
            StringBuilder builder = new StringBuilder();
            for( int i = 0 ; i < fileBytes.Length ; ++i )
            {
                //Get the right char from the table by the byte value
                builder.Append( TRANSLATE_TABLE[ fileBytes[i] ] ) ;
            }
            return builder.ToString();
        }
        /// <summary>
        /// Revert the string
        /// </summary>
        /// <param name="input">The string to revert</param>
        /// <returns>The reverted string</returns>
        public static string Revert( string input )
        {
            StringBuilder builder = new StringBuilder();
            DosHeb.Revert( input , builder );
            return builder.ToString();
        }
        public static string Revert( string input, StringBuilder builder )
        {
            char[] tempChars = input.ToCharArray();
            Array.Reverse( tempChars );
            builder.Append( tempChars );
            return builder.ToString();
        }
        public static string RevertLines( string input )
        {
            StringReader translatedReader = new StringReader( input );
            StringBuilder builder = new StringBuilder();
            for( string line = translatedReader.ReadLine();
                line != null;
                line = translatedReader.ReadLine() )
            {
                DosHeb.Revert( line, builder );
                //Add \r\n to the end of each line
                builder.Append( END_OF_LINE );
            }
            return builder.ToString();
        }
        #endregion Static Methods
        #region Constructors
        /// <summary>
        /// Private Constructor to prevent instances of this class
        /// </summary>
		private DosHeb()
		{
		}
        #endregion Constructors
	}

    public class DBSerialBuilder
	{
		private static XmlTextWriter DBWriter;
		private static int mLectureNum;
		private static int mLastRegNum;

		private DBSerialBuilder()
		{
		}

		/// <summary>
		/// This needs to be called before starting the building.  It creates the blank XML file
		/// and sets the parameters for the writing.
		/// </summary>
		/// <param name="fileName">The filename to create the XML by</param>
		public static void startSerialBuild( string fileName)
		{
			DBWriter = new XmlTextWriter(fileName, Encoding.UTF8);

			DBWriter.Formatting = Formatting.Indented;
			DBWriter.Indentation= 6;
			DBWriter.Namespaces = false;
			
			try
			{
				DBWriter.WriteStartDocument();  // Write the XML header element
				DBWriter.WriteStartElement("", "CourseDB", ""); // Write the root element <CourseDB>
			}
			catch(Exception e)
			{
				Console.WriteLine("Exception: {0}", e.ToString());
			}
		}

		/// <summary>
		/// Call this before any Faculty.  Writes The faculty opening node
		/// </summary>
		/// <param name="facultyName">The Faculty name</param>
		/// <param name="semester">The semester for which it is updated</param>
		public static void startFaculty(string facultyName, string semester)
		{
			if (facultyName == "øôåàéú") // This is a quick hack to overcome a bug in the REP parser
				facultyName = "äðãñä áéå-øôåàéú";
			try
			{
				DBWriter.WriteStartElement("", "Faculty", "");
				DBWriter.WriteAttributeString("name", facultyName);
				DBWriter.WriteAttributeString("semester", semester);
			}
			catch(Exception e)
			{
				Console.WriteLine("Exception: {0}", e.ToString());
			}
		}

		/// <summary>
		/// Call this before any course
		/// </summary>
		/// <param name="courseName">The Course Name</param>
		/// <param name="courseNumber">The Course Number</param>
		/// <param name="courseAcademicPoints">Academic Points</param>
		/// <param name="lectureHours">Number of lecture hours</param>
		/// <param name="tutorialHours">Number of tutorial hours</param>
		/// <param name="labHours">Number of lab hours</param>
		/// <param name="projectHours">nuber of project hours</param>
		public static void startCourse(string courseName, 
									   string courseNumber, 
									   string courseAcademicPoints,
									   string lectureHours,
									   string tutorialHours,
									   string labHours,
									   string projectHours)
        {
			try
			{
				mLectureNum=10; // Initialize Lecture group number counter
				mLastRegNum=11; // Initialize Last Registration Group Number
				DBWriter.WriteStartElement("", "Course", "");
				DBWriter.WriteAttributeString("name", courseName);
				DBWriter.WriteAttributeString("number", courseNumber);
				DBWriter.WriteAttributeString("courseAcademicPoints", courseAcademicPoints);
				if ( lectureHours.Length != 0 )
					DBWriter.WriteAttributeString("lectureHours", lectureHours);
				if ( tutorialHours.Length != 0 )
					DBWriter.WriteAttributeString("tutorialHours", tutorialHours);
				if ( labHours.Length != 0 )
					DBWriter.WriteAttributeString("labHours", labHours);
				if ( projectHours.Length != 0 )
					DBWriter.WriteAttributeString("projectHours", projectHours);
			}
			catch(Exception e)
			{
				Console.WriteLine("Exception: {0}", e.ToString());
			}
		}
		
		/// <summary>
		/// This is actually part of the course node attributes, but is called seperately
		/// because the structure of the rep file was such that it was easier this way.
		/// </summary>
		/// <param name="lecturerInCharge">Lecturer in Charge</param>
		/// <param name="moedADate">Moed A test date</param>
		/// <param name="moedBDate">Moed B test date</param>
		public static void addCourseDetails(string lecturerInCharge,
									 string moedADate,
									 string moedBDate)
		{
			try
			{
				if ( lecturerInCharge.Length != 0)
					DBWriter.WriteAttributeString("lecturerInCharge", lecturerInCharge);
				if ( moedADate.Length != 0)
					DBWriter.WriteAttributeString("moedADate", moedADate);
				else 
					DBWriter.WriteAttributeString("moedADate", DateTime.MinValue.ToShortDateString());
				if ( moedBDate.Length != 0 )
					DBWriter.WriteAttributeString("moedBDate", moedBDate);
				else 
					DBWriter.WriteAttributeString("moedBDate", DateTime.MinValue.ToShortDateString());
			}
			catch(Exception e)
			{
				Console.WriteLine("Exception: {0}", e.ToString());
			}
		}

	
		/// <summary>
		/// Call this before any course event starts
		/// </summary>
		/// <param name="regNumber">The registration group number</param>
		/// <param name="eventType">Lecture/Tutorial/Lab/Project</param>
		/// <param name="teacher">The teacher of this event</param>
		public static void startGroupEvent(	string regNumber,
											string eventType,
											string teacher)
		{
			try
			{
				DBWriter.WriteStartElement("", "CourseEvent", "");
				if (eventType.Length==0)
				{
					eventType="äøöàä";
				}
				if (eventType.Equals("äøöàä")) // Event is a lecture.  Need to feed reg num manually
				{
					regNumber=mLectureNum.ToString();
					mLastRegNum=mLectureNum;
					mLectureNum+=10;
				}
				else // Event is not a lecture.  Need to check if we got a reg number.
				{
					if (regNumber.Length == 0) // Event is not lecture and no reg num was given
					{
						regNumber=mLastRegNum.ToString();
					}
					else // Event is not a lecture, and we got a new reg num.
					{
						mLastRegNum=int.Parse(regNumber);  // Update last registration group number
					}
				}
				
				DBWriter.WriteAttributeString("regNumber", regNumber);
				DBWriter.WriteAttributeString("eventType", eventType);
				DBWriter.WriteAttributeString("teacher", teacher);
			}
			catch(Exception e)
			{
				Console.WriteLine("Exception: {0}", e.ToString());
			}

		}

		/// <summary>
		/// Add an occurence to the current event
		/// </summary>
		/// <param name="EventDay">The day the occurence is on</param>
		/// <param name="StartTime">Starting time in HH.MM format</param>
		/// <param name="Duration">Duration in hours</param>
		/// <param name="Location">Where the occurence is held</param>
		public static void addPlaceTime(string EventDay,
										string StartTime,
										string Duration,
										string Location)
		{
			DBWriter.WriteStartElement("", "PlaceTime", "");

			DBWriter.WriteAttributeString("EventDay", EventDay);
			DBWriter.WriteAttributeString("EventTime", StartTime);
			DBWriter.WriteAttributeString("EventDuration", Duration);
			DBWriter.WriteAttributeString("EventLocation", Location);

			DBWriter.WriteEndElement(); // End Placetime
		}
	
		/// <summary>
		/// Close a course event
		/// </summary>
		public static void closeGroupEvent()
		{
			try
			{
				DBWriter.WriteEndElement(); // End GroupEvent
			}
			catch(Exception e)
			{
				Console.WriteLine("Exception: {0}", e.ToString());
			}
		}

		/// <summary>
		/// Close a course
		/// </summary>
		public static void closeCourse()
		{
			try
			{
				DBWriter.WriteEndElement(); // End Course
			}
			catch(Exception e)
			{
				Console.WriteLine("Exception: {0}", e.ToString());
			}
		}

		/// <summary>
		/// Close a faculty
		/// </summary>
		public static void closeFaculty()
		{
			try
			{
				DBWriter.WriteEndElement(); // End Faculty
			}
			catch(Exception e)
			{
				Console.WriteLine("Exception: {0}", e.ToString());
			}
		}

		/// <summary>
		/// Call this after you finish adding all the information to the database
		/// </summary>
		public static void endSerialBuild()
		{
			try
			{
				DBWriter.WriteEndDocument(); // Close all open tags
				DBWriter.Flush(); // Flush everything in the buffers to the file
			}
			catch(Exception e)
			{
				Console.WriteLine("Exception: {0}", e.ToString());
			}
			if (DBWriter != null)
			{
				DBWriter.Close(); // Close the writer
			}
		}

	}

}